#include <stdio.h>
#include <stdlib.h>

unsigned char maxij (
	unsigned char *src,
	int i,
	int j,
	int row_size
);

unsigned char minij (
	unsigned char *src,
	int i,
	int j,
	int row_size
);

void normalizar_local_c (
	unsigned char *src,
	unsigned char *dst,
	int m, //alto (cant filas)
	int n, //ancho (cant columnas)
	int row_size
) {
	
	for (int j = 0; j<n; j+=1) { //columna
		for (int i = 0; i<m; i+=1) { //fila
			if (i == 0 || i == (m-1) || j == 0 || j == (n-1))
				dst[i*row_size + j] = src[i*row_size + j];
			else
				dst[i*row_size + j] = (src[i*row_size + j] / maxij(src, i, j, row_size) ) + minij(src, i, j, row_size);
		}
	}
}

unsigned char maxij (
	unsigned char *src,
	int i,
	int j,
	int row_size
) {
	unsigned char result = src[(i-1)*row_size + j-1];
	
	if (src[(i-1)*row_size + j] > result)
		result = src[(i-1)*row_size + j];
	
	if (src[(i-1)*row_size + j+1] > result)
		result = src[(i-1)*row_size + j+1];
	
	if (src[i*row_size + j-1] > result)
		result = src[i*row_size + j-1];
	
	if (src[i*row_size + j] > result)
		result = src[i*row_size + j];
	
	if (src[i*row_size + j+1] > result)
		result = src[i*row_size + j+1];

	if (src[(i+1)*row_size + j-1] > result)
		result = src[(i+1)*row_size + j-1];
	
	if (src[(i+1)*row_size + j] > result)
		result = src[(i+1)*row_size + j];
	
	if (src[(i+1)*row_size + j+1] > result)
		result = src[(i+1)*row_size + j+1];
	
	return result;
}

unsigned char minij (
	unsigned char *src,
	int i,
	int j,
	int row_size
) {
	unsigned char result = src[(i-1)*row_size + j-1];
	
	if (src[(i-1)*row_size + j] < result)
		result = src[(i-1)*row_size + j];
	
	if (src[(i-1)*row_size + j+1] < result)
		result = src[(i-1)*row_size + j+1];
	
	if (src[i*row_size + j-1] < result)
		result = src[i*row_size + j-1];
	
	if (src[i*row_size + j] < result)
		result = src[i*row_size + j];
	
	if (src[i*row_size + j+1] < result)
		result = src[i*row_size + j+1];

	if (src[(i+1)*row_size + j-1] < result)
		result = src[(i+1)*row_size + j-1];
	
	if (src[(i+1)*row_size + j] < result)
		result = src[(i+1)*row_size + j];
	
	if (src[(i+1)*row_size + j+1] < result)
		result = src[(i+1)*row_size + j+1];
	
	return result;
}
